package com.pr.levin.prec;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.pr.levin.dataideal.LinkTodatabase;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tv_RegTextlink = null;
    private EditText etUserName = null;
    private EditText etUserPassword = null;
    private Button btnLogin = null;
    private LoadingDialog mLoadingDialog = null;
    private CheckBox pwdChkBox = null;
    private ProgressBar loadingBar = null;
    private Connection conn = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
        initData();
    }

    /**
     * 初始化控件，绑定事务
     */
    private void init() {
        tv_RegTextlink = (TextView) findViewById(R.id.ur_reg);
        etUserName = (EditText) findViewById(R.id.ed_ur);
        etUserPassword = (EditText) findViewById(R.id.ed_pwd);
        pwdChkBox = (CheckBox) findViewById(R.id.bakpwd_chk);
        btnLogin = (Button) findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(this);
        tv_RegTextlink.setOnClickListener(this);
        ImageView userClear_iv = (ImageView) findViewById(R.id.ur_clear);
        ImageView pwdClear_iv = (ImageView) findViewById(R.id.pwd_clear);
        loadingBar = (ProgressBar) findViewById(R.id.loading_bar);

        ViewDealUtils.addClearListener(etUserName, userClear_iv);
        ViewDealUtils.addClearListener(etUserPassword, pwdClear_iv);
    }

    /**
     * 识别是否首次登录，处理记住密码控件选择状态
     * 如有记住密码，放上密码，没有则放上用户名
     */
    private void initData() {
        //是否第一次登录
        if (isFirstLogin()) {
            pwdChkBox.setChecked(false);
        }
        //是否上次有记住密码
        if (isRememberPwd()) {
            pwdChkBox.setChecked(true);
            setUrnameAndUrpwd();
        } else {
            setUrname();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                //输入有用户名则保存用户名，无则不保存
                saveUserName();
                /**
                 * 登录事务，完成要点
                 * 1.判断输入框是否空
                 * 2.连接服务器是否超时判断
                 * 3.用户名和密码验证登录
                 * 4.验证过后，记录状态在本地
                 */
                login();
                break;
            case R.id.ur_reg:
                startActivity(new Intent(LoginActivity.this, RegUserActivity.class));
                break;
        }
    }

    public void saveUserName() {
        String name = ViewDealUtils.getText(etUserName);
        if (!name.equals("")) {
            SharedPreferencesUtils saver = new SharedPreferencesUtils(this, "setting");
            saver.putValues(new SharedPreferencesUtils.ContentValue("name", name));
        }
    }

    public void login() {
        String name = ViewDealUtils.getText(etUserName);
        String pwd = ViewDealUtils.getText(etUserPassword);
        //基本的判断，输入框为空
        if (name.isEmpty() || pwd.isEmpty()) {
            showToast("请输入用户名和密码");
            return;
        }

        showLoading();

        Thread loginRunnable = new Thread() {
            @Override
            public void run() {
                super.run();
//                setLoginBtnClickable(false);
                //睡眠3秒，等待3秒
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //验证账号和密码
                String name = ViewDealUtils.getText(etUserName);
                String pwd = ViewDealUtils.getText(etUserPassword);
                if (name.equals("csdn") && pwd.equals("123456")) {
                    showToast("登录成功");
                    loadCheckBoxState(pwdChkBox);//记录下当前用户记住密码和自动登录的状态;

                    startActivity(new Intent(LoginActivity.this, RegUserActivity.class));
                    finish();//关闭页面
                } else {
                    showToast("输入的登录账号或密码不正确");
                }
                hideLoading();//隐藏加载框
            }
        };
        loginRunnable.start();
    }

    /**
     * 加载等待中..验证账号和密码
     */
    public void showLoading() {
//        if (mLoadingDialog == null) {
//            mLoadingDialog = new LoadingDialog(this, getString(R.string.loading), false);
//        }
//        mLoadingDialog.show();

        //加载登录时进度控件，并设置当前页面其他控件不可点击
        loadingBar.setVisibility(View.VISIBLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }

    public void hideLoading() {
//        if (mLoadingDialog != null) {
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    mLoadingDialog.hide();
//                }
//            });
//        }

        //隐藏加载时的ProgressBar，并且设置页面控件可以点击
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                loadingBar.setVisibility(View.GONE);
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            }
        });
    }

    /**
     * 记录登录成功后的密码和【记住密码】的状态
     *
     * @param checkBox_password 传入【记住密码】的控件
     */
    public void loadCheckBoxState(CheckBox checkBox_password) {

        //获取SharedPreferences对象，使用自定义类的方法来获取对象
        SharedPreferencesUtils helper = new SharedPreferencesUtils(this, "setting");

        //如果设置记住密码
        if (!checkBox_password.isChecked()) { //【记住密码】没有打勾
            //记住密码标识false，密码标识空
            helper.putValues(
                    new SharedPreferencesUtils.ContentValue("rememberPwd", false),
                    new SharedPreferencesUtils.ContentValue("password", ""));
        } else if (checkBox_password.isChecked()) { //【记住密码】打勾 √
            //记住密码标识true，密码获取密码文本框字符，经过加密后保存本地
            helper.putValues(
                    new SharedPreferencesUtils.ContentValue("rememberPwd", true),
                    new SharedPreferencesUtils.ContentValue("password", Base64Utils.encryptBASE64(ViewDealUtils.getText(etUserPassword))));
        }
    }

    public void showToast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });

    }

    /**
     * 点击登录后，设置登录按钮不可点击状态
     *
     * @param clickable 设置true标识该控件可用，false则不可用
     */
    public void setLoginBtnClickable(boolean clickable) {
        btnLogin.setClickable(clickable);
    }

    private boolean isFirstLogin() {
        SharedPreferencesUtils helper = new SharedPreferencesUtils(this, "setting");
        boolean firstlogin = helper.getBoolean("firstlogin", true);
        /**
         * 首次登录的时候，初始化配置文件的参数
         */
        if (firstlogin) {
            helper.putValues(new SharedPreferencesUtils.ContentValue("firstlogin", false),
                    new SharedPreferencesUtils.ContentValue("rememberPwd", false),
                    new SharedPreferencesUtils.ContentValue("name", ""),
                    new SharedPreferencesUtils.ContentValue("password", ""));
            return firstlogin;
        }
        return firstlogin;
    }

    private boolean isRememberPwd() {
        SharedPreferencesUtils helper = new SharedPreferencesUtils(this, "setting");
        boolean isrememberPwd = helper.getBoolean("rememberPwd", false);
        return isrememberPwd;
    }

    private void setUrnameAndUrpwd() {
        etUserName.setText(getLocalUrname());
        etUserPassword.setText("" + getLocalUrpwd());
    }

    public String getLocalUrname() {
        SharedPreferencesUtils helper = new SharedPreferencesUtils(this, "setting");
        String Urname = helper.getString("name");
        return Urname;
    }

    public String getLocalUrpwd() {
        SharedPreferencesUtils helper = new SharedPreferencesUtils(this, "setting");
        String password = helper.getString("password");
        return Base64Utils.decryptBASE64(password);
    }

    private void setUrname() {
        etUserName.setText("" + getLocalUrname());
    }
}